<template>
  <el-drawer v-model="dialogVisible" :title="dialogStatus==='create'?'新增': (dialogStatus === 'view' ? '查看' : '编辑')"
    width="600px" @close="reset">
    <el-form ref="formRef" :model="tableItem" :rules="rules" label-width="180" label-position="top"
      :disabled="!isDisabled">
      <el-form-item label="设备类型:" prop="equipType">
        <el-select v-model="tableItem.equipType" clearable filterable placeholder="请选择" style="width: 200px">
          <el-option v-for="item in equipOption" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="设备编号:" prop="equipNum">
        <el-autocomplete v-model="tableItem.equipNum" :fetch-suggestions="querySearch" clearable style="width: 100%"
          placeholder="请输入设备编号" />
      </el-form-item>

      <el-form-item label="设备数据值:" prop="equipDataValue">
        <el-input v-model="tableItem.equipDataValue" placeholder="请输入设备数据值" style="width: 300px; text-align: right;"
          input-style="text-align:right" />
        <span style="margin-left: 5px;">{{ tableItem.equipType == 1 ? 'kW·h' : 't' }}</span>
      </el-form-item>

      <el-form-item label="采集时间:" prop="collectTime">
        <el-date-picker v-model="tableItem.collectTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择" style="width: 300px" />
      </el-form-item>

    </el-form>
    <template #footer v-if="isDisabled">
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确 定</el-button>
      </span>
    </template>

  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { addEquipCollectData, editEquipCollectData, queryByEquipNum } from '@/api/settle'
import { validate } from '@/utils/validate'

const equipOption = ref<any>([
  { name: '电表', value: 1 },
  { name: '水表', value: 2 },
])

const isDisabled = ref(true)

const tableItem = reactive({
  id: undefined as number | undefined,
  equipType: null,
  equipNum: '',
  equipDataValue: '',
  collectTime: ''
})

const rules = reactive({
  equipType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  equipNum: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
  equipDataValue: [{ required: true, message: '请输入设备数据值', trigger: 'blur' }],
  collectTime: [{ required: true, message: '请选择采集时间', trigger: 'blur' }]
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const reset = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  Object.assign(tableItem, {
    equipType: null,
    equipNum: '',
    equipDataValue: '',
    collectTime: ''
  })
}

const formRef = ref<any>(null)

const emit = defineEmits(['listChange'])

const createData = async () => {

  const valid = await validate(formRef)
  if (valid) {
    const requestData = {
      equipType: tableItem.equipType,
      equipNum: tableItem.equipNum,
      equipDataValue: tableItem.equipDataValue,
      collectTime: tableItem.collectTime
    }
    addEquipCollectData(requestData)
      .then(() => {
        emit('listChange')
        dialogVisible.value = false
        ElMessage.success('添加设备采集数据成功！')
      })
      .catch((err) => {
        ElMessage.error(err.msg || '添加失败')
      })
  }
}

const updateData = async () => {
  const valid = await validate(formRef)
  if (valid) {    
    if (!tableItem.id) {
      ElMessage.error('缺少设备采集数据ID')
      return
    }

    const requestData = {
      id: tableItem.id,
      equipType: tableItem.equipType,
      equipNum: tableItem.equipNum,
      equipDataValue: tableItem.equipDataValue,
      collectTime: tableItem.collectTime
    }

    editEquipCollectData(requestData)
      .then(() => {
        emit('listChange')
        dialogVisible.value = false
        ElMessage.success('更新设备采集数据成功！')
      })
      .catch((err) => {
        ElMessage.error(err.msg)
      })
  }
}

const querySearch = (queryString: string, cb: any) => {
  if (!queryString) {
    return
  }
  const requestData = {
    equipType: tableItem.equipType,
    equipNum: queryString
  }

  queryByEquipNum(requestData)
    .then((res: any) => {
      if (res.success && res.data) {
        cb(res.data.map((item: any) => {
          return { value: item.equipNum }
        }))
      }
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

defineExpose({ dialogVisible, tableItem, isDisabled, dialogStatus, reset })
</script>

<style scoped>
.location-selector {
  width: 100%;
}

.image-preview {
  margin-top: 8px;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>